<template>
  <div v-show="visible">
    <div class="grid_cont">
      <div style="display: flex">
        <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
        <div style="margin-left: 10px; font-size: 16px; line-height: 16px">{{
          formParams.title
        }}</div>
      </div>
      <div style="
          width: 100%;
          height: 1px;
          background-color: rgba(245, 245, 245, 1);
          margin-top: 16px;
          margin-bottom: 30px;
        ">
      </div>
      <el-form ref="formRef" :rules="rules" :model="formParams" style="margin-left: 14px">
        <el-form-item required label="归属区域：" prop="area">
          <el-tree-select v-model="formParams.area" check-strictly placeholder="" :data="optionarea" default-expand-all
            style="width: 320px" />
        </el-form-item>
        <!-- <el-form-item required label="房主：" prop="user" style="margin-left: 28px">
          <el-input v-model="formParams.user" style="width: 320px" />
        </el-form-item> -->
        <el-form-item required label="房主：" prop="user" style="margin-left: 28px">
          <el-select v-model="formParams.user" filterable allow-create placeholder="" placement="bottom"
            style="width: 320px">
            <el-option v-for="item in optionuser" :key="item.id" :value="item.residentName"
              :label="item.residentName" />
          </el-select>
        </el-form-item>
        <el-form-item required label="房号：" prop="houseNumber" style="margin-left: 28px">
          <el-input v-model="formParams.houseNumber" style="width: 320px" />
        </el-form-item>
        <el-form-item required label="房屋类型：" prop="houseType">
          <el-input v-model="formParams.houseType" style="width: 320px" />
        </el-form-item>
        <el-form-item required label="位置：" prop="location" style="margin-left: 28px">
          <el-input v-model="formParams.location" style="width: 320px" />
        </el-form-item>
      </el-form>
    </div>
    <div class="grid_cont2">
      <el-button class="grid_btn" @click="gridCancel" style="
          background-color: rgba(255, 255, 255, 1);
          border: 1px solid rgba(187, 187, 187, 1);
          color: rgba(142, 142, 142, 1);
        ">取消</el-button>
      <el-button class="grid_btn" @click="gridSure"
        style="background-color: #ff9900; border: 1px solid #ff9900; color: #fff">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import * as getgridApi from '@/api/countryside/gridmanagement/index'
const formRef = ref() // 表单 Ref
const formParams = reactive({
  area: '',
  user: '',
  houseNumber: '',
  houseType: '',
  title: '',
  location: ''
})
const houseId = ref(0)
const rules = reactive({
  area: [{ required: true, message: '归属区域不能为空！', trigger: 'change' }],
  user: [{ required: true, message: '户主不能为空！', trigger: 'change' }],
  location: [{ required: true, message: '位置不能为空！', trigger: 'change' }],
  // houseNumber: [{ required: true, message: '房号不能为空！', trigger: 'change' }],
  houseNumber: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('房号不能为空！'))
        } else {
          // 新增房屋
          if (formParams.title === '新增房屋') {
            if (optionhouseid.value.includes(value)) {
              callback(new Error('房号不允许重复！'))
            } else {
              callback()
            }
          }
          // 编辑房屋
          else if (formParams.title === '编辑房屋') {
            // 过滤掉当前正在编辑的房屋的房号
            const filteredOptionhouseid = optionhouseid.value.filter((id) => id !== houseId.value)
            if (filteredOptionhouseid.includes(value)) {
              callback(new Error('房号不允许重复！'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      },
      trigger: 'change'
    }
  ],
  houseType: [{ required: true, message: '房屋类型不能为空！', trigger: 'change' }]
})
const visible = ref(false)
const optionarea = ref([])
const optionuser = ref([])
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object
  }
})

const emit = defineEmits(['getisShow', 'geteditData'])
watch(
  () => props.isShow,
  (val) => {
    visible.value = val
    getAreaOrganization()
  },
  { immediate: true }
)
watch(
  () => props.editData,
  (val) => {
    if (val) {
      formParams.area = val.gridBelonged
      formParams.user = val.houseHolder
      formParams.houseNumber = val.houseNumber
      formParams.location = val.location
      formParams.houseType = val.houseType
      formParams.title = val.dialogtitle
      formParams.location = val.location
      houseId.value = val.houseNumber
    }
    if (props.isShow == true) {
      getHouse()
      getResidentList()
    }
  },
  { immediate: true }
)
const optionhouseid = ref([])
/** 获取房屋类型全列表 */
const getHouse = () => {
  optionhouseid.value = []
  getgridApi.getHouse().then((res) => {
    res.forEach((item) => {
      optionhouseid.value.push(item.houseNumber)
    })
    optionhouseid.value = [...new Set(optionhouseid.value)]
  })
}
// 获取居民信息
const getResidentList = () => {
  getgridApi.getResident().then((res) => {
    optionuser.value = res
  })
}
//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach((node) => {
    if (node.id) {
      node.label = node.gridName
      node.value = node.id
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children)
    }
  })
}
// 获取网格管理列表
let GridList = reactive([])
function getAreaOrganization() {
  optionarea.value = []
  getgridApi.getGridList().then((res) => {
    GridList = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    let cloneData = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    cloneData = cloneData.filter((father) => {
      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter((child) => father.id == child.parentId) // 返回每一项的子级数组
      branchArr.length > 0 ? (father.children = branchArr) : '' //给父级添加一个children属性，并赋值
      return father.parentId == 0 //返回第一层
    })
    traverse(cloneData)
    if (cloneData.length === 0) {
      optionarea.value = res
    } else {
      optionarea.value = cloneData
    }
  })
}
/** 取消按钮操作 */
const gridCancel = () => {
  visible.value = false
  emit('getisShow', visible.value)
  emit('geteditData', props.editData.pageNo)
}
/** 确定按钮操作 */
const gridSure = async () => {
  await formRef.value.validate()
  if (formParams.title === '编辑房屋') {
    GridList.forEach((item) => {
      if (item.gridName === formParams.area) {
        formParams.area = item.id
      }
    })
  }
  const HouseData = {
    gridBelonged: formParams.area,
    houseHolder: formParams.user,
    houseNumber: formParams.houseNumber,
    houseType: formParams.houseType,
    location: formParams.location
  }
  if (formParams.title === '新增房屋') {
    ElMessageBox.confirm('是否确认新增房屋?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        getgridApi.createHouse(HouseData).then((res) => {
          if (res) {
            ElMessage.success('新增成功！')
            emit('geteditData', props.editData.pageNo)
            visible.value = false
            emit('getisShow', visible.value)
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消新增房屋')
      })
  }
  if (formParams.title === '编辑房屋') {
    ElMessageBox.confirm('是否确认编辑房屋?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        HouseData.id = props.editData.id
        getgridApi.updateHouse(HouseData).then((res) => {
          if (res) {
            ElMessage.success('修改成功！')
            emit('geteditData', props.editData.pageNo)
            visible.value = false
            emit('getisShow', visible.value)
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消编辑房屋')
      })
  }
}
onMounted(() => { })
</script>
<style scoped>
.grid_cont {
  min-height: 600px;
  background: #fff;
}

.grid_cont2 {
  width: 100%;
  background: #fff;
  height: 65px;
  justify-content: center;
  align-items: center;
  display: flex;
  padding: 0;
  box-shadow: 0px -2px 6px 0px rgba(188, 188, 188, 0.65);
}

.grid_btn {
  width: 80px;
  height: 30px;
}

.grid_btn:hover {
  opacity: 0.8;
}
</style>
